package com.zmx.patients.view.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.adapter.ChatAdapter;
import com.zmx.patients.adapter.ChatMessageAdapter;
import com.zmx.patients.adapter.OrderImageAdapter;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.pojo.ChatPatients;
import com.zmx.patients.pojo.ChatPojo;
import com.zmx.patients.utils.AllUtil;
import com.zmx.patients.view.util.MySharedPreferences;
import com.zmx.patients.view.util.NestedListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class OrderDetailsActivity extends BaseActivity {

    @BindView(R.id.rl_view)
    RecyclerView rl_view;
    @BindView(R.id.send)
    Button send;
    @BindView(R.id.message)
    EditText message;
    @BindView(R.id.close_order)
    Button closeOrder;
    @BindView(R.id.button_evaluation)
    Button button_evaluation;
    @BindView(R.id.relative)
    RelativeLayout relative;
    private String ask_id, patient_id;

    private List<ChatPojo> list = new ArrayList<>();
    private ChatMessageAdapter chatMessageAdapter;

    private boolean is_evaluation = true;//是否已经评价，默认评价了

    private String hosp_name;
    private String title_name;
    private String class_name;
    private String doctor_name;
    private String doctor_head;

    private String type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_details;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        ask_id = this.getIntent().getStringExtra("ask_id");
        patient_id = this.getIntent().getStringExtra("patient_id");
        hosp_name = this.getIntent().getStringExtra("hosp_name");
        title_name = this.getIntent().getStringExtra("title_name");
        class_name = this.getIntent().getStringExtra("class_name");
        doctor_name = this.getIntent().getStringExtra("doctor_name");
        doctor_head = this.getIntent().getStringExtra("doctor_head");
        type = this.getIntent().getStringExtra("type");

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        rl_view.setLayoutManager(linearLayoutManager);

        if (type == null){

            getData();

        }else{

            getDatas();
        }

    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    Log.e("设计费", "发顺丰" + msg.obj.toString());

                    try {

                        Gson gson = new Gson();
                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONObject jsonObject = object.getJSONObject("data");
                        JSONObject ask = jsonObject.getJSONObject("ask");
                        JSONObject patient = jsonObject.getJSONObject("patient");
                        String sex = "";
                        if (patient.getString("sex").equals("1")) {
                            sex = "男";
                        } else {
                            sex = "女";
                        }
                        String birthday = null;
                        try {

                            SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
                            birthday = AllUtil.getAgeByBirth(s.parse(patient.getString("birthday"))) + "岁";
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }


                        if (ask.getInt("status") == 0) {

                            relative.setVisibility(View.VISIBLE);
                            button_evaluation.setVisibility(View.GONE);


                        } else if (ask.getInt("status") == 1) {

                            relative.setVisibility(View.GONE);
                            button_evaluation.setVisibility(View.VISIBLE);

                            if (ask.getInt("is_comment") == 0) {

                                is_evaluation = false;
                                button_evaluation.setText("我要评价");

                            } else {

                                is_evaluation = true;
                                button_evaluation.setText("已经评价");
                            }

                        } else {

                            relative.setVisibility(View.GONE);
                            button_evaluation.setVisibility(View.VISIBLE);
                            is_evaluation = true;
                            button_evaluation.setText("订单已关闭");

                        }
                        // 字符串转数组  java.lang.String
                        JSONArray imgs = ask.getJSONArray("picture");
                        List<String> image_url = new ArrayList<>();
                        for (int i = 0; i < imgs.length(); i++) {

                            JSONObject object1 = imgs.getJSONObject(i);

                            image_url.add(object1.getString("imgUrl"));
                        }


                        ChatPojo cpj = new ChatPojo();
                        ChatPatients cp = new ChatPatients();
                        cp.setContext(ask.getString("content"));
                        cp.setName("基本信息：" + patient.getString("name") + " | " + sex + " | " + birthday + " | " + patient.getString("weight") + "kg");
                        cp.setImageUrl(image_url);
                        cp.setTime(AllUtil.refFormatNowDate(ask.getString("asktime"), 1));
//                        cp.setDoctor_context(hosp_name+" "+class_name);
                        cp.setHosp_name(hosp_name+" "+class_name);
                        cp.setDoctor_title(title_name);
                        cp.setDoctor_name(doctor_name);
                        cp.setHead_image(doctor_head);

                        cpj.setRole(0);
                        cpj.setChatPatients(cp);
                        list.add(cpj);


                        //字符串转数组  java.lang.String
                        JSONArray chats = jsonObject.getJSONArray("list");
                        for (int i = 0; i < chats.length(); i++) {

                            JSONObject object1 = chats.getJSONObject(i);
                            ChatPojo c = gson.fromJson(object1.toString(), ChatPojo.class);
                            list.add(c);

                        }

                        info();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1) {

                            ChatPojo cp = new ChatPojo();
                            cp.setName(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.name, ""));
                            cp.setReplytime(simpleDateFormat.format(new Date()));
                            cp.setAvatar(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.avatar, ""));
                            cp.setContent(message.getText().toString());
                            cp.setRole(1);
                            list.add(cp);
                            message.setText("");
                            info();
                        }

                        Toast(object.getString("msg"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 3:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));
                        if (object.getInt("code") == 1) {

                            relative.setVisibility(View.GONE);
                            button_evaluation.setVisibility(View.VISIBLE);
                            is_evaluation = true;
                            button_evaluation.setText("订单已关闭");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                case 4:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));
                        if (object.getInt("code") == 1) {

                            relative.setVisibility(View.GONE);
                            button_evaluation.setVisibility(View.VISIBLE);
                            is_evaluation = false;
                            button_evaluation.setText("我要评价");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

            }

        }
    };

    // 更新显示listview
    public void info() {

        if (chatMessageAdapter == null) {

            chatMessageAdapter = new ChatMessageAdapter(this, list,mActivity);
            rl_view.setAdapter(chatMessageAdapter);

        } else {

            chatMessageAdapter.notifyDataSetChanged();
            rl_view.smoothScrollToPosition(list.size());

        }

    }


    /**
     * 获取所有提问
     */
    public void getData() {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "patientAskRecord");
        params.put("data[ask_id]", ask_id);
        params.put("data[patient_id]", patient_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 1, 404);

    }


    /**
     * 获取所有提问
     */
    public void getDatas() {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "teamRecord");
        params.put("data[patient_id]", patient_id);
        params.put("data[ask_id]", ask_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.team/entry", params, handler, 1, 404);

    }

    /**
     * 获取所有提问
     */
    public void send() {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(message.getText().toString());
        ls.add("0");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "patientAskReply");
        params.put("data[ask_id]", ask_id);
        params.put("data[content]", message.getText().toString());
        params.put("data[type]", "0");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 2, 404);

    }

    /**
     * 获取所有提问
     */
    public void sends() {


        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(message.getText().toString());
        ls.add("0");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "replyAsk");
        params.put("data[ask_id]", ask_id);
        params.put("data[content]", message.getText().toString());
        params.put("data[type]", "0");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.team/entry", params, handler, 2, 404);

    }
    /**
     * 关闭订单
     */
    public void closeAsk() {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add("完成");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "closeAsk");
        params.put("data[ask_id]", ask_id);
        params.put("data[cause]", "完成");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 3, 404);

    }
    /**
     * 关闭订单
     */
    public void closeAsks() {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add("完成");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "closeTeamAsk");
        params.put("data[ask_id]", ask_id);
        params.put("data[cause]", "完成");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.team/entry", params, handler, 3, 404);

    }
    /**
     * 完成订单
     */
    public void askComplete() {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "askComplete");
        params.put("data[ask_id]", ask_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 4, 404);

    }
    /**
     * 完成订单
     */
    public void askCompletes() {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "teamAskComplete");
        params.put("data[ask_id]", ask_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.team/entry", params, handler, 4, 404);

    }


    @OnClick({R.id.close_order, R.id.send, R.id.button_evaluation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.close_order:

                AlertDialog alertDialog1; //信息框
                final String[] items = {"关闭订单", "完成订单"};
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                alertBuilder.setTitle("请选择操作");
                alertBuilder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        if (i == 0) {

                            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                            builder.setTitle("关闭后无法追问医生问题");
                            builder.setNegativeButton("确定关闭", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    if (type == null){

                                        closeAsk();

                                    }else{

                                        closeAsks();
                                    }

                                }
                            });
                            builder.setPositiveButton("取消关闭", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder.show();
                        } else if (i == 1) {

                            if (type == null){

                                askComplete();

                            }else{

                                askCompletes();
                            }


                        }

                    }
                });
                alertDialog1 = alertBuilder.create();
                alertDialog1.show();


                break;
            case R.id.send:

                if (message.getText().toString().equals("")) {
                    Toast("请输入内容");
                    return;
                }


                if (type == null){

                    send();

                }else{

                    sends();
                }

                break;

            case R.id.button_evaluation:

                if (is_evaluation) {
                    return;
                }

                Bundle bundle = new Bundle();
                bundle.putString("ask_id", ask_id);
                bundle.putString("type", type);
                startActivity(OrderEvaluationActivity.class, bundle, 100);

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100) {

            if (data != null) {
                String state = data.getStringExtra("state");
                if (state.equals("1")) {

                    is_evaluation = true;
                    button_evaluation.setText("已经评价");
                }
            }

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
